from django.http import JsonResponse
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from apps.users.models import User
from meiduo import settings


def generate_verify_token(user_id, email):
    serializer = Serializer(settings.SECRET_KEY, 3600 * 24 * 2)
    token = serializer.dumps({"user_id": user_id, "email": email})
    token = token.decode()

    return token


def chack_verify_token(token):
    serializer = Serializer(settings.SECRET_KEY, 3600 * 24 * 2)

    try:
        user_id_dict = serializer.loads(token)
    except Exception as e:
        print("捕获异常", e)
    else:
        user_id = user_id_dict.get("user_id")
        email = user_id_dict.get("email")
        print(user_id, "-----", email)
        try:
            user = User.objects.get(id=user_id, email=email)
        except Exception as e:
            print("不匹配", e)
        else:
            return user


if __name__ == '__main__':
    token = generate_verify_token('vic123', "1248849985@qq.com")
    print(token)
    bb = chack_verify_token(
        "eyJhbGciOiJIUzUxMiIsImlhdCI6MTYxODgzNzYyMiwiZXhwIjoxNjE5MDEwNDIyfQ.eyJ1c2VyX2lkIjoidmljMTIzIiwiZW1haWwiOiIxMjQ4ODQ5OTg1QHFxLmNvbSJ9.hQYv4WuvFzQFjnlcVjs4M9Q2J-fJPyuSI1X9Lsbf2AIseJtiePIPCrGnrHIXdiajERmNa6GpdbzyYkfsvZ6WtQ")
    print(bb)
    # print(aa)
